package com.xtayfjpk.security.ldap;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.junit.Test;

public class LDAPTest {
	
	public LdapContext createContext() throws Exception {
		String ldapFactory = "com.sun.jndi.ldap.LdapCtxFactory";  
	    String ldapUrl = "ldap://192.168.0.203:389/";// url  
	    String ldapPwd = "wombat";//密码  
	    Hashtable<String, String> env = new Hashtable<>();  
	    env.put(Context.INITIAL_CONTEXT_FACTORY, ldapFactory);  
	    // LDAP server  
	    env.put(Context.PROVIDER_URL, ldapUrl);  
	    env.put(Context.SECURITY_AUTHENTICATION, "simple");  
	    //env.put(Context.SECURITY_PRINCIPAL, "cn=Manager,dc=example,dc=com"); //  填DN 
	    //env.put(Context.SECURITY_PRINCIPAL, "cn=Person,cn=lisi,dc=example,dc=com"); //  填DN 
	    env.put(Context.SECURITY_PRINCIPAL, "uid=scott,ou=people,dc=example,dc=com"); //  填DN 
	    env.put(Context.SECURITY_CREDENTIALS, ldapPwd); // AD Password
	   // env.put("java.naming.ldap.attributes.binary", "objectSid objectGUID"); 
	    LdapContext context = new InitialLdapContext(env, null);
	    return context;
	}
	
	@Test
	public void testQuery() throws Exception {
		LdapContext context = createContext();
		SearchControls controls = new SearchControls();
		controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		String searchFilter = "objectClass=organizationalRole";
		String returnedAtts[] = {"distinguishedName", "objectGUID", "name"};
		controls.setReturningAttributes(returnedAtts);
		String baseName = "dc=example,dc=com";//基准目录，dc=example,dc=com为根目录
		NamingEnumeration<SearchResult> enumeration = context.search(baseName, searchFilter, controls);
		while(enumeration.hasMore()) {
			SearchResult result = enumeration.next();
			System.out.println(result);
			/*System.out.println(result.getClassName());
			System.out.println(result.getName());
			System.out.println(result.getNameInNamespace());
			System.out.println(result.getObject());
			System.out.println(result.getAttributes());*/
		}
	}
}
